#coding=utf8
import json

from flask import request, g

from .cookies import get_cookie, del_cookie, set_cookie



def add_flash(message, category="message"):
    if '_flash' not in g:
        g._flash = {}

    g._flash.setdefault(category, []).append(message)


def add_flashs(messages, category="message"):
    if '_flash' not in g:
        g._flash = {}

    g._flash.setdefault(category, []).extend(messages)


def get_flashs(with_category=False, category_filter=[]):
    if not category_filter:
        category_filter = ['message']

    if '_old_flash' not in g:
        g._old_flash = {}

    flashes = {k: v for k, v in g._old_flash.items() if k in category_filter}

    if with_category:
        return flashes
    else:
        return reduce(lambda x,y:x+y, flashes.values(), [])


def load_flashs():
    val = get_cookie('_flash')
    if val:
        del_cookie('_flash')
        g._old_flash = json.loads(val)


def save_flashs():
    if '_flash' in g and g._flash:
        val = json.dumps(g._flash)
        set_cookie('_flash', val)
